﻿@model Nop.Web.Models.ShareBuy.ShareBuyModel
@using Nop.Web.Framework
@using Nop.Web.Models.ShareBuy;
@using Telerik.Web.Mvc.UI;
@Html.ValidationSummary(true)

@{
    //register CSS and JS
    Html.AddCssFileParts("~/Administration/Content/fileuploader.css");
    Html.AddScriptParts("~/Administration/Scripts/fileuploader.js");
}
<script type="text/javascript">
    var authToken = '@(this.Context.Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)';
    var pictureTemplate="<li>"+
            "<div class='s-img'>"+
                "<img width='300' src='{#imageUrl}'><input type='hidden' class='hidPictureId' value='{#PictureId}' /></div>"+
            "<div class='s-set'>"+
                    "<div>"+
                        "<input type='radio' checked='checked' class='cover' value='{#PictureId}' name='cover' id='rad{#PictureId}'><label for='rad{#PictureId}'>Set to cover</label></div>"+
                    "<div class='set-item'>"+
                        "<label>Order</label>"+
                        "<input class='order' type='text' value='0' />"+
                    "</div>"+
                    "<div class='set-item'>"+
                        "<input type='button' value='Delete' class='del' shareBuyPictureId='0' pictureId='{#PictureId}' onclick='deletePictureItem(this)'></div>"+
            "</div>"+
            "</li>";
    $(document).ready(function () {
        $('#addShareBuy').click(function () {
            //validate
            if($.trim($("#Products").val())=="")
            {
                alert("Product is requested.");
                return;
            }
            if($.trim($("#Title").val())==""){
                alert("Title is requested.");
                return;
            }
            if($("#pictureSets li").length<3||$("#pictureSets li").length>10) {
                alert("Please upload 3-10 pictures.");
                return;
            }
            saveShareBuy();
        });

        var canceledUploadQueueId="";
        var uploader = new qq.FileUploader({
            element: document.getElementById('uploadPicture'),
            sizeLimit:1024 * 1024 * 15,//15M
            action: '@(Url.Content("~/Admin/Picture/AsyncUpload"))',
            onComplete: function(id, fileName, responseJSON){
                if(canceledUploadQueueId.indexOf(id,0)<0)
                {
                    if (responseJSON.success) {
                        var pictureItemHtml=pictureTemplate.replace(new RegExp("{#PictureId}",'g'),responseJSON.pictureId);
                        pictureItemHtml=pictureItemHtml.replace(new RegExp("{#imageUrl}",'g'),responseJSON.imageUrl);
                        $("#pictureSets").append(pictureItemHtml);
                    } else {
                        alert(responseJSON.error);
                    }
                }
            },
            onCancel: function (id, fileName) { 
                canceledUploadQueueId=canceledUploadQueueId+id+",";
            },
            strings: {
                upload: "@T("Common.FileUploader.Upload")",
                drop: "@T("Common.FileUploader.DropFiles")",
                cancel: "@T("Common.FileUploader.Cancel")",
                failed: "@T("Common.FileUploader.Failed")"
            }
        });
    });

    function deletePictureItem(btnObj)
    {
        if(confirm("Sure delete?"))
        {
            var shareBuyPictureId=$(btnObj).attr("shareBuyPictureId");
            var pictureId=$(btnObj).attr("pictureId");
            var url="";
            var data="";
            if(shareBuyPictureId>0)
            {
                url="@Url.Content("~/sharebuypicture/delete/")"+shareBuyPictureId;
            }
            else
            {
                url="@Url.Content("~/picture/delete/")"+pictureId;
            }

            $(btnObj).attr('disabled', true);
            $.ajax({
                cache:false,
                type: "POST",
                url: url,
                data:data,
                success: function (data) {
                    if(data.Result)
                    {
                        alert("Delete successfully.")
                        var li=$(btnObj).parent().parent().parent();
                        if(li.find(".cover").attr("checked")=="checked")
                        {
                            $("#pictureSets li .cover:first").attr("checked","checked");
                        }
                        li.remove();

                    }
                    else
                    {
                        alert('Failed to delete picture.')
                    }
                },
                error:function (xhr, ajaxOptions, thrownError){
                    alert('Failed to delete picture.')
                    $(btnObj).attr('disabled', false);
                }  
            });
            
        }
    }

    function saveShareBuy()
    {
        $("#addShareBuy").attr("disabled","disabled");
        var title=$.trim($("#Title").val());
        var description=$.trim($("#Description").val());
        var picturesJSON=getPicturesJSON();
        var productId=$("#Products").val();
        var categoryId=$("#Categories").val();

        $(this).attr('disabled', true);
        $.ajax({
            cache:false,
            type: "POST",
            dataType:"json",
            url: "@Url.Action("Save", "ShareBuy")",
            data: { "id": @Model.Id,"categoryId":categoryId,"orderId":@Model.OrderId, "productId": productId, "cutomerId": @Model.CustomerId,"title":title,"description":description,"picturesJSON":picturesJSON,"defaultPictureId":$("#pictureSets input[name='cover']:checked").val() },
            success: function (data) {
                if(data.Result)
                {
                    window.location.href="/sharebuy/detail/"+data.Id;
                    $(this).attr('disabled', false);
                }
                else
                {
                    $(this).removeAttr('disabled');
                    alert('Failed to add Sharing.')
                }
            },
            error:function (xhr, ajaxOptions, thrownError){
                $(this).removeAttr('disabled');
                alert('Failed to add Sharing.')
            }  
        });
    }

    function getPicturesJSON()
    {
        var ret="[";
        var items="";
        $("#pictureSets li").each(function(){
            items=items+"{\"PictureId\":"+$(this).find(".hidPictureId").val()+",\"PictureUrl\":\""+$(this).find(".s-img img").attr("src")+"\",\"DisplayOrder\":"+$.trim($(this).find(".order").val())+"},";
        });
        if(items!="")
        {
            items=items.substring(0,items.length-1);
        }
        ret=ret+items+"]";
        return ret;
    }
</script>
<div id="addshare">
    <div class="title">
        <h2>Share</h2>
    </div>
    <div class="content">
        <div class="readme">
            <ul>
                <li><strong>About Sharing：</strong>You can feel the use of choose and buy suggest real photos usage scenario unpacking
                            process with net friends share;</li>

            </ul>
        </div>
        <div class="forms">
            <div class="item fore  ">
                <div class="tit">
                    @Html.LabelFor(model => model.ProductVariantSelectList)<s>*</s>:
                </div>
                <div class="i-item">
                    @Html.DropDownList("Products", Model.ProductVariantSelectList, "Choose an product")
                </div>
            </div>
            <div class="item">
                <div class="tit">
                    @Html.LabelFor(model => model.CategorySelectList)<s>*</s>:
                </div>
                <div class="i-item">
                    @Html.DropDownList("Categories", Model.CategorySelectList, "Choose an category")
                </div>
            </div>
            <div class="item">
                <div class="tit">
                    @Html.LabelFor(model => model.Title)<s>*</s>:
                </div>
                <div class="i-item">
                    @Html.EditorFor(model => model.Title)
                    @Html.ValidationMessageFor(model => model.Title)
                </div>
            </div>
            <div class="item text">
                <div class="tit">
                    @Html.LabelFor(model => model.Description):
                </div>
                <div class="i-item">
                    @Html.TextAreaFor(model => model.Description, new { style = "Width: 580px; Height: 150px;" })
                    @Html.ValidationMessageFor(model => model.Description)
                    <div id="v_c" class="tips">
                        You can input 1000 words at most, including a blank space.
                    </div>
                </div>
            </div>
            <div class="item" style="margin-top: 32px;">
                <div class="tit">
                    Pictures:<s>*</s>
                </div>
                <div class="i-item">
                    <div class="tips">
                        Please upload 3-10 pictures. Each picture not more than 15 m, support picture format
                                for JPG, jpeg, BMP, PNG, GIF.
                    </div>
                    <div id="uploadPicture">
                        <noscript>
                            <p>
                                Please enable JavaScript to use file uploader.
                            </p>
                            <!-- or put a simple form for upload here -->
                        </noscript>
                    </div>
                </div>
            </div>
            <div class="item">
                <!--Pictures list start!-->
                <div class="i-item">
                    <ul id="pictureSets" class="s-list">
                        @if (Model.ShareBuyPictureModels.Count > 0)
                        {
                            foreach (var picture in Model.ShareBuyPictureModels)
                            {
                            <li>
                                <div class="s-img">
                                    <img width="300" src="@picture.PictureUrl"><input
                                                    type="hidden" value="@picture.PictureId" class="hidPictureId">
                                </div>
                                <div class="s-set">
                                    <div>
                                        <input type="radio" id="rad#@picture.PictureId" name="cover" value="@picture.PictureId" class="cover" @if (picture.PictureId == Model.DefaultPictureId)
                                                                                                                                              {@Html.Raw("checked='checked'");
                                                                                                                                              }><label
                                                        for="rad#@picture.PictureId">Set to cover</label>
                                    </div>
                                    <div class="set-item">
                                        <label>
                                            Order</label><input type="text" value="@picture.DisplayOrder" class="order">
                                    </div>
                                    <div class="set-item">
                                        <input type="button" onclick="deletePictureItem(this)" shareBuyPictureId="@picture.Id" pictureId="@picture.PictureId" class="del" value="Delete">
                                    </div>
                                </div>
                            </li>
                            }
                        }
                    </ul>
                </div>
                <!--Pictures list end!-->
            </div>
            <div class="item">
                <div class="i-item" style="text-align: right;">
                    <input id="addShareBuy" type="button" class="button-10" value="Submit" />
                </div>
            </div>
        </div>
        
    </div>
</div>
